package demo.dbconnection;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Properties;
import java.util.Scanner;
import java.util.logging.FileHandler;
import java.io.*;

import org.apache.log4j.*;

import demo.logger.*;

public class DBConnection
{
	private static Connection conn;
	private static Statement statement;
	private static String url;

	public DBConnection()
	{

		// 加载数据库配置文件
		InputStream inputStream = this.getClass().getClassLoader()
				.getResourceAsStream("demo/config/DatabaseConfig.properties");
		Properties p = new Properties();
		try
		{
			p.load(inputStream);
			LoggerHelper.debug("DBConnection", "读取数据库配置");
		} catch (IOException e)
		{
			e.printStackTrace();
		}

		url = "jdbc:mysql://" + p.getProperty("host") + ":"
				+ p.getProperty("port") + "/" + p.getProperty("database") + "?"
				+ "user=" + p.getProperty("user") + "&password="
				+ p.getProperty("password")
				+ "&useUnicode=true&characterEncoding="
				+ p.getProperty("Encoding");
		LoggerHelper.info("DBConnection", "DBConnection加载完成");
		LoggerHelper.debug("DBConnection", "url = " + url);
	}

	public static void open()
	{

		try
		{

			Class.forName("com.mysql.jdbc.Driver");// 加载数据库驱动

			conn = DriverManager.getConnection(url);// 链接到数据库

			statement = conn.createStatement();// 声明statement类

			LoggerHelper.debug("DBConnection", "成功加载MySQL驱动程序");

		} catch (SQLException e)
		{
			LoggerHelper.error("DBConnection", "数据库操作错误");
			e.printStackTrace();
		} catch (Exception e)
		{
			LoggerHelper.error("DBConnection", "程序运行错误");
			e.printStackTrace();
		}
	}

	public static void update(String sql)
	{
		try
		{
			statement.executeUpdate(sql);
		} catch (SQLException e)
		{
			LoggerHelper.error("DBConnection.update", "更新数据库错误");
			e.printStackTrace();
		}
	}

	public static ResultSet query(String sql)
	{
		try
		{
			ResultSet rs = statement.executeQuery(sql);
			return rs;
		} catch (SQLException e)
		{
			LoggerHelper.error("DBConnection.query", "查询数据库错误");
			e.printStackTrace();
		}
		return null;
	}

	public static void close() throws SQLException
	{
		conn.close();
	}
}
